package com.sec.etech.bpm.config;


import net.javacrumbs.shedlock.core.LockProvider;
import net.javacrumbs.shedlock.provider.jdbctemplate.JdbcTemplateLockProvider;
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.sql.DataSource;
import java.util.Date;

/**
 * Schedule配置文件
 * 增加简单Lock机制（同一数据库的同一个lock名只有一个实例执行，规避多服务时同时执行问题）
 * 去掉schedule条件启动配置
 */
@Configuration
@EnableScheduling
//@ConditionalOnProperty(prefix = "etech.scheduling", name = "enabled", havingValue = "true", matchIfMissing = true)
@EnableSchedulerLock(defaultLockAtMostFor = "PT5M", defaultLockAtLeastFor="PT5M")
@EnableAsync
public class ScheduleConfig {

    @Bean
    public LockProvider lockProvider(DataSource dataSource) {
        return new JdbcTemplateLockProvider(
                JdbcTemplateLockProvider.Configuration.builder()
                        .withJdbcTemplate(new JdbcTemplate(dataSource))
                        .usingDbTime() // Works on Postgres, MySQL, MariaDb, MS SQL, Oracle, DB2, HSQL and H2
                        .build()
        );
    }

    /*@Scheduled(fixedDelay = 180000)
    @SchedulerLock(name = "myscheduledTask")
    public void scheduleFixedDelayTask() {
        System.out.println("Fixed delay task - " + new Date());
    }*/

}
